// JavaScript Document
/**********************************************************
上传多个文件
option
{
	file:'.upload', //文件id
	ele:'#uploadContainer', //容器id
	file_max_size:'4', //单位为M
	file_chunk_size:'4', //分片大小
	file_progress_txet:'上传进度', //上传进度文字
	file_name_txet:'', //文件名称文字
	rootPath:"index.php"//ajax访问时的根路径
	chunkShow:false//是否显示分片的进度


}
**********************************************************/
var uploadQiniu = qiniu;
function fileUploads(option)
{
	option = arguments[0] ? arguments[0] : {};

	var fileId =option['file'] ? option['file'] : ".uploadFile";

	var chunkSize = option['file_chunk_size'] ? option['file_chunk_size'] : 4;
	var maxSize = option['file_max_size'] ? option['file_max_size'] : 100;

	var files = $(fileId);
	option['chunkShow'] = option['chunkShow'] ===true ? true : false;

	var fileContainer = addUploadBox(option); //文件容器

	files.unbind("change").bind("change",function(){

		fileContainer.html("");

		var uploadFiles = this.files;

		if(option['start']  && typeof option['start']=='function'){
            option['start']();
        }

		if(uploadFiles)
		{

			 for(var i=0;i<uploadFiles.length;i++)
			 {
				   addUploadBoard(fileContainer,uploadFiles[i],chunkSize,maxSize);
			 }


			 selectfileUpload(fileContainer,uploadFiles,option);

		}


	})

}

/**********************************************************
上传单个文件
fileContainer 显示文件的容器 jq对象
uploadFiles 文件数组
option 基本配置
**********************************************************/
function selectfileUpload(fileContainer,uploadFiles,option)
{

	 var file = fileContainer.find('.file');

	 var fileIndex=null,fileInfo=null,finish=null;
	 var rootPath = option['rootPath'] ? option['rootPath'] : "index.php";

	 var chunkSize = option['file_chunk_size'] ? option['file_chunk_size'] : 4;
	 var maxSize = option['file_max_size'] ? option['file_max_size'] : 100;

	 for(var i = 0;i<file.length ;i++)
	 {
		  finish = $(file[i]).data('finish')
		  if(! finish)
		  {
			  fileIndex = i;
			  break;
		  }
	 }

	 if(fileIndex!==null)
	 {
		 fileInfo = uploadFiles[fileIndex];

		 if(fileInfo)
		 {

			 fileName = fileInfo.name;
			 board = $(file[fileIndex]);

			 if(option['file_start']  && typeof option['file_start']=='function'){
               option['file_start'](fileName,board);
             }

			 $.getJSON(rootPath+"/upload/Uploads/get_token", {saveName:fileName}, function(res){
			     if(res && res.err == 0 && res.content && res.content.server && res.content.token)
				 {
					   var count = fileInfo.size / (chunkSize * 1024 * 1024);
					   var chunksStr= "";

					   count = count < 1 ? parseInt(count) : Math.ceil(count);

					   if(count > 0 && option['chunkShow'])
					   {
							   for(var i=0 ; i<count ; i++)
							   {
								   chunksStr=chunksStr+"<div style='height:30px;width: 30px;background: #ccc;border-radius: 5px;position: relative;float:left;margin-right: 10px;margin-top: 10px;'><div style='height:0%;width: 100%;background: orange;border-radius: 5px;position: absolute;bottom: 0px;left: 0px;' class='chunkProgress'></div></div>";
							   }

							   board.find('.chunks').html(chunksStr);

					   }

					   switch(res.content.server) {
							 case "Qiniu":

							    var savename = res.content.savename;
                                qiniuUpload(board,fileInfo,res.content.token,fileContainer,uploadFiles,option,savename);
								break;
							 case "Local":
							    var savename = res.content.savename;
								localUpload(board,fileInfo,res.content.token,fileContainer,uploadFiles,option,savename);
								break;
							 default:

						}
				 }
				 else
				 {
					  alert(fileName+"文件有误");
					  board.data('finish','err');
				 }
			 });
		 }

	 }
	 else
	 {
		 if(option['complete']  && typeof option['complete']=='function'){
            option['complete']();
         }
	 }


}
/**********************************************************
七牛上传多个文件
board 当前上传节点对象
**********************************************************/
function qiniuUpload(board,file,token,fileContainer,uploadFiles,option,savename)
{
	var finishedAttr = [];
	var compareChunks = [];
	var putExtra = {params:{"x:name":""}};
	var file_name = file.name,file_size = file.size;
	var observable;
	var rootPath = option['rootPath'] ? option['rootPath'] : "index.php";
	var uploadButton = ".control-upload", //上传按钮
	    uploadProgress = ".progress",//进度条
		uploadProgressText = ".progressText",//进度条文字
		uploadChunkGroup=".chunks"//分块进度容器
		uploadChunk=".chunkProgress"//分块进度
	/**********************************************************
	获取七牛上传配置
	useCdnDomain: 表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
	disableStatisticsReport: 是否禁用日志报告，为布尔值，默认为false。
	region: 选择上传域名区域；当为 null 或 undefined 时，自动分析上传域名区域
	retryCount: 上传自动重试次数（整体重试次数，而不是某个分片的重试次数）；默认 3 次（即上传失败后最多重试两次）；目前仅在上传过程中产生 599 内部错误时生效，但是未来很可能会扩展为支持更多的情况。
	concurrentRequestLimit: 分片上传的并发请求量，number，默认为3；因为浏览器本身也会限制最大并发量，所以最大并发量与浏览器有关。
	checkByMD5: 是否开启 MD5 校验，为布尔值；在断点续传时，开启 MD5 校验会将已上传的分片与当前分片进行 MD5 值比对，若不一致，则重传该分片，避免使用错误的分片。读取分片内容并计算 MD5 需要花费一定的时间，因此会稍微增加断点续传时的耗时，默认为 false，不开启。
	**********************************************************/
	var config = {
      useCdnDomain: true,
      disableStatisticsReport: false,
      retryCount: 3
    };

	//putExtra.params["x:name"] = file_name.split(".")[0];
	//putExtra.fname = file;
	putExtra.mimeType = null;


    // 设置next,error,complete对应的操作，分别处理相应的进度信息，错误信息，以及完成后的操作
    var error = function(err) {
        board.find(uploadProgressText).text("失败");
		board.data('finish','err');

        selectfileUpload(fileContainer,uploadFiles,option);


		if(option['file_error']  && typeof option['file_error']=='function'){
            option['file_error'](file_name,board);
        }
    };



    var complete = function(res) {


		board.find(uploadChunkGroup).remove();
        board.find(uploadButton).remove();
		board.data('finish','finish');
		board.find(uploadProgressText).text("成功");
		selectfileUpload(fileContainer,uploadFiles,option);

		$.getJSON(rootPath+"/upload/Uploads/save_file", {filename:res.filename,filesize:res.filesize,path:res.path,server:"Qiniu"}, function(res){
			  var returnData = res;
			  if(option['file_complete']  && typeof option['file_complete']=='function'){
					option['file_complete'](returnData,board);
			  }
		})

		console.log(res);

    };

      var next = function(response) {
			var chunks = response.chunks||[];
			var total = response.total;
			// 这里对每个chunk更新进度，并记录已经更新好的避免重复更新，同时对未开始更新的跳过
			for (var i = 0; i < chunks.length; i++) {
				  if (chunks[i].percent === 0 || finishedAttr[i]){
					 continue;
				  }
				  if (compareChunks[i].percent === chunks[i].percent){
					 continue;
				  }
				  if (chunks[i].percent === 100){
					  finishedAttr[i] = true;
				  }

				  board.find(uploadChunkGroup).find(uploadChunk).eq(i).css("height",parseInt(chunks[i].percent) + "%");
			}

			board.find(uploadProgressText).text(parseInt(total.percent) + "% ");
			board.find(uploadProgress).css("width",parseInt(total.percent) + "%");
			compareChunks = chunks;

			if(option['file_progress']  && typeof option['file_progress']=='function'){
                 option['file_progress'](file_name,total.percent,board);
            }
      };


      var subObject = { next: next,error: error,complete: complete};
      var subscription;
      // 调用sdk上传接口获得相应的observable，控制上传和暂停
      observable = qiniu.upload(file, savename, token, putExtra, config);

	  subscription = observable.subscribe(subObject);
}


/**********************************************************
本地上传
board 当前上传节点对象
**********************************************************/
function localUpload(board,file_,token,fileContainer,uploadFiles,option,savename)
{


	var chunkSize = option['file_chunk_size'] ? option['file_chunk_size'] : 4;
	var maxSize = option['file_max_size'] ? option['file_max_size'] : 100;
    var  file = file_;

	var file_name = file.name,file_size = file.size;

	var xhr = new XMLHttpRequest();

    const LENGTH = 1024 * 1024 * chunkSize;

    var blob_num = 0;
    var is_stop = 0;
	var retryCount= 3,retryCount_=0;

	var rootPath = option['rootPath'] ? option['rootPath'] : "index.php";
	var uploadButton = ".control-upload", //上传按钮
	    uploadProgress = ".progress",//进度条
		uploadProgressText = ".progressText",//进度条文字
		uploadChunkGroup=".chunks"//分块进度容器
		uploadChunk=".chunkProgress"//分块进度

	sendFile()

    //切割文件 chunkNum 当前的分片编号
    function cutFile(){

	  var start = 0,end=0,file_blob="";
	  start = blob_num * LENGTH;
	  end = (blob_num + 1) * LENGTH;
      file_blob = file.slice(start,end);

	  //console.log(blob_num);
      return file_blob;

    };

 //发送文件
    function sendFile(){

      var total_blob_num = Math.ceil(file_size / LENGTH);

	  var blob = cutFile();

      var form_data = new FormData();

      form_data.append('file',blob);
      form_data.append('blob_num',blob_num + 1);
      form_data.append('total_blob_num',total_blob_num);
      form_data.append('savename',file_name);


	  xhr.upload.onprogress = function(evt) {
		  if(!evt.lengthComputable) return false;
		  var per = Math.floor((evt.loaded / evt.total) * 100);
		 // console.log((blob_num+1)+"/"+per)

		  if(option['chunkShow']){
			  board.find(uploadChunkGroup).find(uploadChunk).eq(blob_num).css("height",per + "%");
		  }

		  var percent = ((blob_num * LENGTH + evt.loaded) / file_size) *100;
		  board.find(uploadProgressText).text(parseInt(percent) + "% ");
		  board.find(uploadProgress).css("width",parseInt(percent) + "%");

		  if(option['file_progress']  && typeof option['file_progress']=='function'){
                 option['file_progress'](file_name,percent,board);
          }
	  }


      xhr.open('POST',rootPath+"/upload/Uploads/save_blob_file",true);
      xhr.onreadystatechange = function () {

		  if (xhr.status == "200" && xhr.readyState == 4) {
              var res = $.parseJSON(xhr.responseText);
		      var err = res.err;
			  err =0;
			  if(err === 0 )
			  {
				  if(blob_num < (total_blob_num-1) && is_stop === 0){
					  blob_num += 1;
					  form_data = null;
					  sendFile(blob_num)
				  }
				  else if(blob_num >= (total_blob_num-1) )
				  {
						board.find(uploadChunkGroup).remove();
						board.find(uploadButton).remove();
						board.data('finish','finish');
						board.find(uploadProgressText).text("成功");
						selectfileUpload(fileContainer,uploadFiles,option);

						var returnData = res.content;
						if(option['file_complete']  && typeof option['file_complete']=='function'){
							  option['file_complete'](returnData,board);
					    }
				  }
			  }
			  else
			  {
				  if(retryCount_ > retryCount)
				  {
						board.find(uploadProgressText).text("失败");
						board.data('finish','err');

						selectfileUpload(fileContainer,uploadFiles,option);


						if(option['file_error']  && typeof option['file_error']=='function'){
							option['file_error'](file_name,board);
						}
				  }
				  else
				  {
					  sendFile(blob_num);
					  retryCount_++;
				  }
			  }
		  }
      }


      xhr.send(form_data);
    }



}
/**********************************************************
将上传文件添加到文档节点中
**********************************************************/
function addUploadBoard(fileContainer,file,chunkSize,maxSize) {


  var fileSize = file.size,fileName = file.name,zise = fileSize / 1024;
  var chunksStr="",progressStr="",containerStr="";

  if(zise >=1024)
  {
	  zise = zise / 1024;
	  zise = zise.toFixed(2)+" M"
  }
  else
  {
	  zise = zise.toFixed(2)+" Kb"
  }



  progressStr = "<div style='height: 20px;'><span style='width: 50px;float: left;color: orange;margin-top: 4px;align:right' class='progressText'>0%</span><div style='width:75%;height: 15px;position: relative;top: 10%;left: 3px;float: left;background: #ccc;border-radius: 5px;'><div style='width:0%;height: 15px;position: relative;background: orange;border-radius: 5px;' class='progress'></div></div></div><div style='width: 100%;position: relative;' class='chunks'></div>";

  containerStr="<div style='display: flex;margin-top: 10px' class='file'><div style='flex: 1;width: 30%'>"+fileName+"("+zise+")</div><div style='flex: 1;width: 70%'><div style='position: relative;width: 100%;'>"+progressStr+"</div></div><div>";

  fileContainer.append(containerStr);

  //return board;
}





/**********************************************************
将上传文件添加到文档节点中
**********************************************************/
function addUploadBox(option) {

	 option = arguments[0] ? arguments[0] : {};

 var containerId =  option["ele"] ? option["ele"] : "#uploadContainer";
 var file_name =  option["file_name_txet"] ? option["file_name_txet"] : "文件名";
 var file_progress =  option["file_progress_txet"] ? option["file_progress_txet"] : "上传进度";
 var container = $(containerId);
 var containerStr = "";
 containerStr = "<div class='fileUploadBox' style='padding-left:10%;padding-right:10%'><div style='display:flex;border-bottom: 1px solid #e8e8e8'><div style='flex: 1;height: 60px;line-height: 60px; width: 30%'>"+file_name+"</div><div style='flex: 1;height: 60px;line-height: 60px;width: 70%'>"+file_progress+"</div></div><div class='fileContainer'></div></div>";

 container.html(containerStr);

 return container.find(".fileContainer");

}

